<template>
    <div>
        <p>在线：
            <van-switch size="24px" :value="checked" :loading="loading" @input="onInput" />
            <van-button type="primary" size="small" text="查看记录" @click="show_record" />
        </p>

        <van-overlay :show="show" @click="show=false;records=null">
            <div class="wrapper">
                <van-loading color="#1989fa" v-if="!records" />
                <div class="block" @click.stop v-else>
                    <div style="border-bottom: 1px solid #eee" v-for="(v,i) in records" :key="i">
                        <p>{{v.room}}:{{v.nickname}}</p>
                        <p>{{v.text}}</p>
                        <p>{{v.time}}</p>
                    </div>
                </div>
            </div>
        </van-overlay>
    </div>
</template>

<script>
    import { Switch,Overlay,Loading,Button } from 'vant';
    export default {
        name: "SocketSwitch",
        components:{
            [Switch.name]: Switch,
            [Overlay .name]: Overlay ,
            [Loading .name]: Loading ,
            [Button .name]: Button ,
        },
        props: {
            socket: {
                type: Object,
                default: ()=>null
            }
        },
        data(){
            return {
                show: false,
                records: null,
                loading: false,
                checked: false
            }
        },
        methods:{
            onInput(){
                this.loading=true;
                if(this.checked){
                    this.$props.socket.disconnect()
                    this.loading=false;
                    this.checked=false;
                } else{
                    this.$props.socket.emit("reconnect")
                }
            },
            show_record(){
                this.$data.show=true;
                this.$props.socket.emit("get_records")
            },
        },
        watch: {
            socket: function(new_socket){
                if(new_socket){
                    this.$data.checked= new_socket.json.connected;
                    new_socket.on("connect",()=>{
                        this.loading=false;
                        this.checked=true;
                    });
                    new_socket.on("get_records",(v)=>{
                        this.$data.records=v;
                    })
                }
            },
        },
        mounted(){
        }
    }
</script>

<style scoped>
    .wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }

    .block {
        width: 80%;
        height: 80%;
        background-color: #fff;
        overflow-y: auto;
    }
</style>
